import { Button, Card, Col, Form, Input, message, Row, Select, Spin } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import '../common/taskStyles.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { useContext, useEffect } from 'react';
import { getColorTextLoadMap } from '@/utils';
import Cls from 'classnames';
import { UploadFormCommon } from '@/components/UploadForm';
import { completeService, resolveTaskService } from '../services';
import { WorkflowCheckRecordContext } from '../common';
export const WorkflowHandTasks: React.FC<IWorkflowChedkRecordAPI.IWorkflowHandTasks> = ({
  detailInfoObj,
  requestController,
  reloadCallback,
  handHelpType = false, // true:帮办  false:办理 默认
  pageHeight = 0.4,
  isShowDrawer,
}) => {
  const prefixCls: string = 'workflow-handtasks-';

  const { isCheckDrawer } = useContext(WorkflowCheckRecordContext);

  /**
   * 表单
   */
  const [handleFlowForm] = Form.useForm();

  /**
   * 初始化
   */
  useEffect(() => {
    if (detailInfoObj?.msequenceFlowList && detailInfoObj?.msequenceFlowList?.length > 0) {
      let num = 0;
      if (isShowDrawer?.resObj == 'false') num = 1;

      const { colorText } = getColorTextLoadMap(detailInfoObj?.msequenceFlowList?.[num]?.flowName);

      handleFlowForm?.setFieldsValue({
        intention: detailInfoObj?.msequenceFlowList?.[num]?.flowValue,
        comment: colorText,
      });
    }
  }, [detailInfoObj]);

  /**
   * 办理流程回调
   * @param res
   */
  const completeCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入办理流程接口
   */
  const { completeLoading, completeRun } = completeService(completeCallBack, requestController);

  /**
   * 引入帮办流程接口
   */
  const { resolveTaskLoading, resolveTaskRun } = resolveTaskService(completeCallBack, requestController);

  /**
   * 保存
   */
  const onSaveHand = () => {
    handleFlowForm?.validateFields()?.then((values: any) => {
      const intentionItem: Record<string, any> = detailInfoObj?.msequenceFlowList?.find((item: any) => item?.flowValue == values?.intention);
      const params: any = {
        ...values,
        ...intentionItem,
        id: detailInfoObj?.id,
        orderID: detailInfoObj?.orderID,
        taskIsSign: detailInfoObj?.taskIsSign,
        procInstID: detailInfoObj?.procInstID,
        procDefID: detailInfoObj?.procDefID,
      };

      if (handHelpType) {
        resolveTaskRun(params);
      } else {
        completeRun(params);
      }
    });
  };

  return (
    <div
      style={{
        height: isCheckDrawer ? '100%' : document.body.clientHeight * pageHeight,
      }}
    >
      <Card
        title={'流程办理'}
        className={pageStyles['page-view-cardView']}
        bodyStyle={{
          padding: '10px 0px 0px',
        }}
      >
        <Spin spinning={completeLoading || resolveTaskLoading}>
          <Row className={'cardBodyRow'}>
            <Col span={24} className={'cardBodyCol'}>
              <ScrollBarLayout>
                <div
                  className={Cls(pageStyles['fromView-stylesPage'], prefixCls + 'taskHandleFormBox')}
                  style={{
                    padding: '5px 10px',
                  }}
                >
                  <Form form={handleFlowForm}>
                    <Row>
                      <Col span={24}>
                        <Form.Item
                          name="intention"
                          label="审批意向"
                          rules={[
                            {
                              required: true,
                              message: '请选择审批意向',
                            },
                          ]}
                          initialValue={detailInfoObj?.msequenceFlowList?.[0]?.flowValue}
                        >
                          <Select
                            placeholder="请选择审核意向"
                            onSelect={(selectKey: string, otherInfo: any) => {
                              handleFlowForm?.setFieldsValue({
                                comment: otherInfo?.children,
                              });
                            }}
                          >
                            {detailInfoObj?.msequenceFlowList?.map((item: any) => {
                              const { colorText } = getColorTextLoadMap(item?.flowName);
                              return (
                                <Select.Option key={item?.flowValue} value={item?.flowValue}>
                                  {colorText}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item
                          label={'批注'}
                          name="comment"
                          rules={[
                            {
                              required: true,
                              message: '请输入批注',
                            },
                          ]}
                        >
                          <Input.TextArea placeholder={`请输入批注`} showCount maxLength={500} autoSize={{ minRows: 2, maxRows: 4 }} />
                        </Form.Item>
                      </Col>

                      <UploadFormCommon
                        form={handleFlowForm}
                        fileFormName={'attachUrl'}
                        spanCol={24}
                        inRowProportion={24}
                        name={'attachFile'}
                        label="附件"
                        required={false}
                        accept={'.jpg|.png|.jpeg|.doc|.docx'}
                        url={`/${requestController}/uploadFile`}
                        downloadUrl={`/${requestController}/downloadFile`}
                        fileFormDelName={'delLicenceUrl'}
                        delFunc={() => {}}
                        maxFile={1}
                        defaultFiles={null}
                      >
                        上传附件
                      </UploadFormCommon>

                      <Col span={24}>
                        <Form.Item label={'附件描述'} name="attachDescribe">
                          <Input.TextArea placeholder={`请输入附件描述`} showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </div>
              </ScrollBarLayout>
              <div className={'cardBodybtn'}>
                <Button type={'primary'} onClick={onSaveHand}>
                  {handHelpType ? '帮办' : '确认'}
                </Button>
              </div>
            </Col>
          </Row>
        </Spin>
      </Card>
    </div>
  );
};
